package com.ruoyi.purchase.service.impl;

import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.mapper.AuditMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.*;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.mapper.CompanyOtherMapper;
import com.ruoyi.company.utils.Util;
import com.ruoyi.company.utils.pdf.HtmlToPdf;
import com.ruoyi.company.utils.pdf.ImgToPdf;
import com.ruoyi.manufacturer.domain.DjManufacturer;
import com.ruoyi.manufacturer.mapper.DjManufacturerMapper;
import com.ruoyi.paramters.domain.Parameter;
import com.ruoyi.paramters.mapper.ParameterMapper;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.mapper.ProcurementOrderMapper;
import com.ruoyi.product.domain.AICode;
import com.ruoyi.product.domain.PictureMemory;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.mapper.AICodeMapper;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.productProof.domain.ProductProof;
import com.ruoyi.productProof.mapper.ProductProofMapper;
import com.ruoyi.purchase.domain.PurchaseModel;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.mapper.SaleorderMapper;
import com.ruoyi.salesInvoice.domain.SalesInvoiceOrder;
import com.ruoyi.salesInvoice.mapper.SalesInvoiceMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购订单
 *
 * @author songjz
 */
@Service
public class PurchaseOrderServiceImpl implements PurchaseOrderService {

    @Autowired
    DjManufacturerMapper djManufacturerMapper;

    @Autowired
    SalesInvoiceMapper salesInvoiceMapper;

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private AuditMapper auditMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ParameterMapper parameterMapper;

    @Autowired
    private ProcurementOrderMapper procurementOrderMapper;

    @Autowired
    private SaleorderMapper saleorderMapper;

    @Autowired
    private SaleGoodsMapper saleGoodsMapper;

    @Autowired
    private ProductProofMapper productProofMapper;

    @Autowired
    private AICodeMapper aiCodeMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private CompanyOtherMapper companyOtherMapper;

    @Override
    public int auditSale(PurchaseOrder purchaseOrder) {
        PurchaseOrder purchaseOrder1 = purchaseOrderMapper.selectPurchaseOrderById(purchaseOrder.getPurchaseId());
        purchaseOrder.setPurchaseStatus(purchaseOrder.getPurchaseStatus());
        int num = 0;
        if (purchaseOrder.getPurchaseStatus() != null && !purchaseOrder.getPurchaseStatus().equals("")) {
            purchaseOrder.setAuditTime(DateUtils.getNowDate());
        }

        if (purchaseOrder.getPurchaseStatus().equals("1")) {
            purchaseOrder1.setPurchaseStatus(purchaseOrder.getPurchaseStatus());
            num = purchaseOrderMapper.updatePurchaseOrder(purchaseOrder1);

            //将pdf上传到服务器 并且更新 pdfurl字段
            purchaseTopdf(purchaseOrder.getPurchaseId(), SecurityUtils.getDeptId());
        } else {
            purchaseOrder1.setPurchaseStatus(purchaseOrder.getPurchaseStatus());
            num = purchaseOrderMapper.updatePurchaseOrder(purchaseOrder1);
        }

        return num;
    }

    public void purchaseTopdf(Long purchaseId, Long deptId) {
//        int sbsoluteY = 470;
        int sbsoluteY = 400;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("purchaseId", purchaseId);
        hashMap.put("deptId", deptId);
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderByMap(hashMap);
        //供方 信息;
        Company purchaseData = companyMapper.selectByCompanyId(purchaseOrder.getSupplierId());
        //CompanyInvoice purchaseInvoiceData = companyInvoiceMapper.selectByCompanyId(purchaseOrder.getSupplierId());
        //需方 信息;
        Company demanderData = companyMapper.selectByCompanyId(purchaseOrder.getDeptId());

        //CompanyInvoice demanderInvoiceData = companyInvoiceMapper.selectByCompanyId(purchaseOrder.getDeptId());

        String fileName = purchaseOrder.getPurchaseNum() + "(" + System.currentTimeMillis() + ")" + ".pdf";
        String downloadPath = RuoYiConfig.getDownloadPath();
        File file1 = new File(downloadPath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        File file = new File(downloadPath + "/purchaseTopdf");
        if (!file.exists()) {
            file.mkdir();
        }
        String destPath = downloadPath + "purchaseTopdf/" + fileName;
        String aaaa = downloadPath + "purchaseTopdf/";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(destPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        StringBuilder str = new StringBuilder();
        str.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        str.append("<html lang=\"zh\" xmlns=\"http://www.w3.org/1999/xhtml\">");
        str.append("<head>\n" +
                "    <meta charset=\"UTF-8\"></meta>\n" +
                "    <title>Title</title>\n" +
                "</head>\n" +
                "<body style=\"font-family:SimSun;\">");

        str.append("<table width=\"680px\">");
        str.append("<tr>");
        str.append("<td style=\"color: black;font-size: 25px;font-weight: bold;\"><div align=\"center\">采购合同</div></td>");
        str.append("</tr>");
        str.append("</table>");

        str.append("<table width=\"850px\">");
        str.append("<tbody>");
        str.append("<tr>");
        str.append("<td width=\"50%\" align=\"left\"></td>");
        str.append("<td width=\"50%\" align=\"left\">合同编号：" + purchaseOrder.getPurchaseNum() + "</td></tr>");
        str.append("<tr><td>供货方（甲方）：" + sysDeptMapper.selectDeptById(purchaseOrder.getSupplierId()).getDeptName() + "</td>");
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        str.append("<td>签订日期：" + fmt.format(purchaseOrder.getPurchaseDate()) + "</td></tr>");
        str.append("<tr><td>采购方（乙方）：" + sysDeptMapper.selectDeptById(purchaseOrder.getDeptId()).getDeptName() + "</td>");
        //签订地点
        Map map = new HashMap();
        map.put("deptId", purchaseOrder.getDeptId());
        map.put("companyId", purchaseOrder.getSupplierId());
        map.put("gradeStatus", "02");
        CompanyOther companyOther = companyOtherMapper.selectByCompanyIdAndDeptId(map);
        if (companyOther == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
            throw new RuntimeException("您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
        }
        str.append("<td>签订地点：" + purchaseData.getRasCity() + "</td></tr>");
        str.append("</tbody></table>");

        str.append("<table width=\"830px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td width=\"100%\" >\n" +
                "                        一、货物名称及价格\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody>\n" +
                "            </table>");

        str.append("<table width=\"680px\" style=\"border-spacing: 0;border-collapse: collapse;\">\n" +
                "                <tr>\n" +
                "                    <td width=\"20%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            存货名称\n" +
                "                        </div>\n" +
                "                    </td >\n" +
                "                    <td width=\"15%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            生产厂家\n" +
                "                        </div>\n" +
                "                    </td >\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            规格型号\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"6%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            单位\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"8%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            数量\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"10%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            含税单价\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            含税金额\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            备注\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                </tr>\n");
        //总数量
        int totalNum = 0;
        for (int i = 0; i < purchaseOrder.getPurchaseModel().size(); i++) {
            sbsoluteY = sbsoluteY - 18;
            PurchaseModel purchaseModel = purchaseOrder.getPurchaseModel().get(i);
            str.append("<tr>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getProductName() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 13px;\">" + purchaseModel.getManufacturerName() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getProductType() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getUnit() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getPurchaseNum() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getTaxPrice() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getTaxTotal() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                    "                </tr>");

            totalNum += purchaseOrder.getPurchaseModel().get(i).getPurchaseNum();
        }
        str.append("                <tr>\n" +
                "                    <td style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 16px;\">\n" +
                "                            合计\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\">" + totalNum + "</td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\">" + purchaseOrder.getTaxAmount() + "</td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                </tr>\n" +
                "            </table>");

        //合计人民币
        BigDecimal taxamount = purchaseOrder.getTaxAmount();
        double saleorderTaxamount = taxamount.doubleValue();
//        String upperCase = Util.upperCase(saleorderTaxamount);
        String upperCase = Util.upperCases(saleorderTaxamount);
        str.append("<table width=\"850px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;width:70%;;border: 0;!important;\">\n" +
                "                        合计人民币(大写)：" + upperCase + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody></table>\n");

        //合同约定项
        String contractTerms = companyOther.getContractTerms();
        if (contractTerms == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您与该公司的合同约定项为空,请先在基础信息-合作单位管理-编辑功能完善与该公司的合同约定项。");
            throw new RuntimeException("您与该公司的合同约定项为空,请先在基础信息-合作单位管理-编辑功能完善与该公司的合同约定项。");
        }
//        if (contractTerms == null) {
//            contractTerms = "二、交货时间：甲方收到货款后，当日或第二个工作日发货。\n" +
//                    "三、运输及费用承担方式：物流送货至乙方指定地址，甲方承担运费。\n" +
//                    "四、货款结算方式：乙方以电汇方式汇款，款到发货。开具13%增值税专用发票\n" +
//                    "五、质保与违约责任：须为生产企业原厂出品，原装进口，并符合中国医疗器械管理政策，否则无\n" +
//                    "条件退货退款。\n" +
//                    "六、质量验收时效：请先验货，再签收物流。签收后视为验收合格。\n" +
//                    "七、本协议法律争议管辖地为山东省济南市。\n" +
//                    "八、合同一式两份，双方签字盖章后生效。扫描件具有同等法律效力。";
//        }

        //根据回车进行分割
        String[] contractTermsArr = new String[]{};
        contractTermsArr = contractTerms.split("\\r?\\n");

        str.append("<br></br>");
        str.append("<table width=\"850px\" id=\"contractTerms\">");
        for (int i = 0; i < contractTermsArr.length; i++) {
            sbsoluteY = sbsoluteY - 12;
            //每行81个字符
            String[] strings = Util.stringToArray(contractTermsArr[i]);
            String interception = Util.interception(strings, 80);
            //根据回车进行分割
            String[] split = interception.split("换行aaaaa");
            for (int j = 0; j < split.length; j++) {
                String s = split[j];
                System.out.println(s);
                str.append(s);
                str.append("<br></br>");
            }
        }
        str.append("</table>");
        str.append("<br></br>");

        str.append("<table width=\"680px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td width=\"45%\" align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        甲&nbsp;&nbsp;&nbsp;&nbsp;方：" + sysDeptMapper.selectDeptById(purchaseOrder.getSupplierId()).getDeptName() + "\n" +
                "                    </td>\n" +
                "                    <td width=\"45%\" align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        乙&nbsp;&nbsp;&nbsp;&nbsp;方：" + sysDeptMapper.selectDeptById(purchaseOrder.getDeptId()).getDeptName() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;white-space:normal;word-break:break-all;\">\n" +
                "                        地&nbsp;&nbsp;&nbsp;&nbsp;址：" + purchaseData.getRasProvince() + purchaseData.getRasCity() + purchaseData.getRasDistrict() + purchaseData.getRasAddress() +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;white-space:normal;word-break:break-all;\">\n" +
                "                        地&nbsp;&nbsp;&nbsp;&nbsp;址：" + demanderData.getRasProvince() + demanderData.getRasCity() + demanderData.getRasDistrict() + demanderData.getRasAddress() +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        邮&nbsp;&nbsp;&nbsp;&nbsp;编：\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        邮&nbsp;&nbsp;&nbsp;&nbsp;编：\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        电&nbsp;&nbsp;&nbsp;&nbsp;话：" + purchaseData.getCorporateRegisterPhone() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        电&nbsp;&nbsp;&nbsp;&nbsp;话：" + demanderData.getCorporateRegisterPhone() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        统一社会信用代码：" + purchaseData.getSocialCreditCode() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        统一社会信用代码：" + demanderData.getSocialCreditCode() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        开&nbsp;&nbsp;&nbsp;&nbsp;户：" + purchaseData.getDepositBank() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        开&nbsp;&nbsp;&nbsp;&nbsp;户：" + demanderData.getDepositBank() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        账&nbsp;&nbsp;&nbsp;&nbsp;号：" + purchaseData.getBankNumber() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        账&nbsp;&nbsp;&nbsp;&nbsp;号：" + demanderData.getBankNumber() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        签约代表：" + purchaseData.getCorporateRepresentative() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        签约代表：" + demanderData.getCorporateRepresentative() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody>\n" +
                "            </table>");

        str.append("</body></html>");

        PurchaseOrder purchaseOrder1 = new PurchaseOrder();
        purchaseOrder1.setPurchaseId(purchaseOrder.getPurchaseId());
        String[] split = destPath.split("nyterp");

        String string = aaaa + "sale" + fileName;
        String[] split3 = string.split("nyterp");
        purchaseOrder1.setPdfUrl("/purchaseTopdf/采购合同" + fileName);
        purchaseOrderMapper.updatePurchasePdf(purchaseOrder1);
        //生成PDF
        HtmlToPdf.createPdfByHtml(fileOutputStream, str.toString());

        //判断 该两个公司 是否 上传了 印章  如果没有上传 则自动生成一个印章
        String purchaseSealUrl = "";
        String saleSealUrl = "";
        //供方
        if (!"".equals(purchaseData.getElectronicSealUrl()) && purchaseData.getElectronicSealUrl() != null) {
            purchaseSealUrl = purchaseData.getElectronicSealUrl();
        } else {
//            if (!"".equals(purchaseData.getSealUrl()) && purchaseData.getSealUrl() != null) {
//                purchaseSealUrl = purchaseData.getSealUrl();
//            } else {
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = purchaseData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String pngPath = RuoYiConfig.getDownloadPath();
////                File file2 = new File(pngPath);
////                if (!file2.exists()) {
////                    file2.mkdir();
////                }
////                File pngfile = new File(pngPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = pngPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(sysDeptMapper.selectDeptById(purchaseData.getCompanyId()).getDeptName(), purchaseData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////
////                Company company = new Company();
////                company.setSealUrl("/seal/" + imgname);
////                company.setCompanyId(purchaseData.getCompanyId());
////                //更新url
////                purchaseSealUrl = "/seal/" + imgname;
////                companyMapper.updateCompany(company);
//            }
        }

        //需方  也就是采购
        if (!"".equals(demanderData.getElectronicSealUrl()) && demanderData.getElectronicSealUrl() != null) {
            saleSealUrl = demanderData.getElectronicSealUrl();
        } else {
//            if (!"".equals(demanderData.getSealUrl()) && demanderData.getSealUrl() != null) {
//                saleSealUrl = demanderData.getSealUrl();
//            } else {
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = demanderData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String pngPath = RuoYiConfig.getDownloadPath();
////                File pngfile = new File(pngPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = pngPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(sysDeptMapper.selectDeptById(demanderData.getCompanyId()).getDeptName(), demanderData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company = new Company();
////                company.setSealUrl("/seal/" + imgname);
////                company.setCompanyId(demanderData.getCompanyId());
////                //更新url
////                saleSealUrl = "/seal/" + imgname;
////                companyMapper.updateCompany(company);
//            }
        }

        String downloadPath1 = RuoYiConfig.getDownloadPath();
        String uploadPath = RuoYiConfig.getUploadPath();
        String purUrl = "";
        String saleUrl = "";

        String purImgPath = "";
        String saleImgPath = "";

        if (!"".equals(purchaseData.getElectronicSealUrl()) && purchaseData.getElectronicSealUrl() != null) {
            purUrl = purchaseSealUrl;
            String[] split1 = purUrl.split("/profile/upload");
            purImgPath = uploadPath + split1[1];
        } else {
            purImgPath = downloadPath1 + purchaseSealUrl;
        }

        if (!"".equals(demanderData.getElectronicSealUrl()) && demanderData.getElectronicSealUrl() != null) {
            saleUrl = saleSealUrl;
            String[] split1 = saleUrl.split("/profile/upload");
            saleImgPath = uploadPath + split1[1];
        } else {
            saleImgPath = downloadPath1 + saleSealUrl;
        }

        String fileStr = downloadPath1 + "purchaseTopdf/" + fileName;
        String fileStr1 = downloadPath1 + "purchaseTopdf/2" + fileName;
        String fileStr3 = downloadPath1 + "purchaseTopdf/采购合同" + fileName;

        try {
            if (!purchaseSealUrl.equals("")) {
                //左边照片
                ImgToPdf.imgToPdfLeft(fileStr, fileStr1, purImgPath, sbsoluteY);
            } else {
                ImgToPdf.imgToPdf(fileStr, fileStr1);
            }
            if (!saleSealUrl.equals("")) {
                //右边照片
                ImgToPdf.imgToPdfRight(fileStr1, fileStr3, saleImgPath, sbsoluteY);
            } else {
                ImgToPdf.imgToPdf(fileStr1, fileStr3);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        try {
//            ImgToPdf.imgToPdf(fileStr, fileStr3);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //删除fileStr fileStr1
        File filePath1 = new File(fileStr);
        if (filePath1.exists()) {
            filePath1.delete();
        }
        File filePath2 = new File(fileStr1);
        if (filePath2.exists()) {
            filePath2.delete();
        }


    }

    /**
     * 查询采购订单
     *
     * @param purchaseOrder 查询条件
     * @return 结果
     */
    @Override
    public List<PurchaseOrder> selectPurchaseOrderList(PurchaseOrder purchaseOrder) {
        if (SecurityUtils.getLoginUser().getUser().getCompanyId() == null) {
            List<PurchaseOrder> purchaseOrders = new ArrayList<PurchaseOrder>();
            return purchaseOrders;
        }
        purchaseOrder.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        return purchaseOrderMapper.selectPurchaseOrderList(purchaseOrder);
    }

    /**
     * 添加采购订单
     *
     * @param purchaseOrder 添加信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPurchaseOrder(PurchaseOrder purchaseOrder) {
        Product product1 = new Product();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        //创建采购订单
        purchaseOrder.setCreateBy(sysUser.getNickName());
        purchaseOrder.setDeptId(sysUser.getCompanyId());
        purchaseOrderMapper.insertPurchaseOrder(purchaseOrder);
        if (purchaseOrder.getPurchaseModel() != null) {
            try {
                purchaseOrderMapper.insertPurchaseModel(purchaseOrder);
            } catch (Exception e) {
                purchaseOrderMapper.deletePurchaseOrderById(purchaseOrder.getPurchaseId());
                return 0;
            }
        }

        //添加审核订单
        Audit audit = new Audit();
        audit.setOrderId(purchaseOrder.getPurchaseId());
        audit.setCompanyId(sysUser.getCompanyId());
        audit.setOrderType("1");
        audit.setAuditStatus("0");
        audit.setUserId(purchaseOrder.getUserId());
        audit.setSupplierId(purchaseOrder.getSupplierId());
        audit.setTaxAmount(purchaseOrder.getTaxAmount());
        //订单编号
        audit.setOrderNum(purchaseOrder.getPurchaseNum());
        auditMapper.insertAudit(audit);

        //创建新的产品信息添加到自己的公司产品目录下
        if (purchaseOrder.getPurchaseModel() != null) {
            List<PurchaseModel> purchaseModel = purchaseOrder.getPurchaseModel();
            Long supplierId = purchaseOrder.getSupplierId();
            for (PurchaseModel model : purchaseModel) {
                Long productId1 = model.getProductId();
                product1.setProductId(productId1);
                product1.setDeptId(supplierId);
                List<Product> productList = productMapper.selectProductList(product1);
                //通过产品型号唯一码查询产品信息 集合
                String modelCode = model.getModelCode();
                ProductModel productModelList = productMapper.selectProductByModelCode(supplierId, modelCode);
                if (productMapper.selectProductByModelCode(sysUser.getCompanyId(), modelCode) != null) {
                    continue;
                } else {
                    //查询供应商的产品注册证
                    Product productProof = new Product();
                    productProof.setDeptId(supplierId);
                    productProof.setProductId(model.getProductId());
                    List<Product> productProofs = productMapper.selectProductProofList(productProof);
                    if (productProofs.size() != 0) {
                        int count = 0;
                        for (Product proof : productProofs) {
                            Product product2 = new Product();
                            product2.setDeptId(sysUser.getCompanyId());
                            product2.setMedicalNumber(proof.getMedicalNumber());
                            if (productMapper.selectProductProofList(product2).size() != 0) {
                                if (productMapper.selectProductByModelCode(sysUser.getCompanyId(), modelCode) != null) {
                                    continue;
                                }
                                Long productId = productMapper.selectProductProofList(product2).get(0).getProductId();
                                //查询图片集合
                                List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(productModelList.getModelNo());
                                //查询生产商信息，判断是否带回信息
                                DjManufacturer djManufacturer = djManufacturerMapper.selectDjManufacturerById(productModelList.getManufacturerId());
                                djManufacturer.setCompanyId(sysUser.getCompanyId());
                                DjManufacturer manufacturers = djManufacturerMapper.selectDjManufacturerOne(djManufacturer);
                                if (manufacturers == null) {
                                    djManufacturer.setManufacturerId(null);
                                    int i = djManufacturerMapper.insertDjManufacturer(djManufacturer);
                                    productModelList.setManufacturerId(djManufacturer.getManufacturerId());
                                } else {
                                    int i = djManufacturerMapper.updateDjManufacturer(djManufacturer);
                                    productModelList.setManufacturerId(manufacturers.getManufacturerId());
                                }
                                //插入产品规格信息
                                productModelList.setProductId(productId);
                                productModelList.setDeptId(sysUser.getCompanyId());
                                productModelList.setCreateBy(sysUser.getNickName());
                                productMapper.insertProductModel(productModelList);
                                //循环赋值将产品规格中图片信息
                                if (pictureMemoryList.size() != 0) {
                                    for (PictureMemory pictureMemory : pictureMemoryList) {
                                        pictureMemory.setPictureNo(null);
                                        pictureMemory.setModelNo(productModelList.getModelNo());
                                    }
                                    productMapper.insertPictureMemory(pictureMemoryList);
                                }
                                count = 0;
                                continue;
                            } else {

                                count++;
                            }
                        }
                        if (count != 0) {
                            for (Product product : productList) {
                                product.setProductId(productId1);
                                product.setDeptId(sysUser.getCompanyId());
                                product.setCreateBy(sysUser.getNickName());
                                productMapper.insertProductId(product);
                            }

                            //将供应商的产品的条形码信息带到本公司下
                            AICode aiCode = new AICode();
                            aiCode.setDeptId(supplierId);
                            aiCode.setProductId(productId1);
                            //供应商的产品条形码信息
                            List<AICode> aiCodes = aiCodeMapper.selectAICode(aiCode);
                            aiCode.setDeptId(sysUser.getCompanyId());
                            //本公司下的条形码信息
                            List<AICode> aiCodes1 = aiCodeMapper.selectAICode(aiCode);
                            if (aiCodes1.size() != 0) {
                                for (Product product : productList) {
                                    if (aiCodes.size() != 0) {
                                        for (AICode code : aiCodes) {
                                            code.setDeptId(sysUser.getCompanyId());
                                            code.setProductId(product.getProductId());
                                        }
                                        //  aiCodeMapper.updateAICodeList(aiCodes);
                                    }
                                }

                            } else {
                                if (aiCodes.size() != 0) {
                                    for (Product product : productList) {
                                        for (AICode code : aiCodes) {
                                            code.setDeptId(sysUser.getCompanyId());
                                            code.setProductId(product.getProductId());
                                        }
                                        aiCodeMapper.insertAICodeList(aiCodes);
                                    }

                                }
                            }
                            //将供应商下的产品注册证,带到本公司下
                         /*   for (Product proof : productProofs) {

                                proof.setDeptId(sysUser.getCompanyId());
                                proof.setProductId(product.getProductId());
                                productMapper.insertProduct(proof);

                            }*/
                            List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(productModelList.getModelNo());
                            //查询生产商信息，判断是否带回信息
                            DjManufacturer djManufacturer = djManufacturerMapper.selectDjManufacturerById(productModelList.getManufacturerId());
                            djManufacturer.setCompanyId(sysUser.getCompanyId());
                            DjManufacturer manufacturers = djManufacturerMapper.selectDjManufacturerOne(djManufacturer);
                            if (manufacturers == null) {
                                djManufacturer.setManufacturerId(null);
                                int i = djManufacturerMapper.insertDjManufacturer(djManufacturer);
                                productModelList.setManufacturerId(djManufacturer.getManufacturerId());
                            } else {
                                int i = djManufacturerMapper.updateDjManufacturer(djManufacturer);
                                productModelList.setManufacturerId(manufacturers.getManufacturerId());
                            }
                            productModelList.setProductId(productList.get(0).getProductId());
                            productModelList.setDeptId(sysUser.getCompanyId());
                            productModelList.setCreateBy(sysUser.getNickName());
                            productMapper.insertProductModel(productModelList);
                            //插入产品图片信息
                            if (pictureMemoryList.size() != 0) {
                                for (PictureMemory pictureMemory : pictureMemoryList) {
                                    pictureMemory.setPictureNo(null);
                                    pictureMemory.setModelNo(productModelList.getModelNo());
                                }
                                productMapper.insertPictureMemory(pictureMemoryList);
                            }
                        } else {
//                            //将供应商的产品的条形码信息带到本公司下
//                            AICode aiCode = new AICode();
//                            aiCode.setDeptId(supplierId);
//                            aiCode.setProductId(productId1);
//                            //供应商的产品条形码信息
//                            List<AICode> aiCodes = aiCodeMapper.selectAICode(aiCode);
//                            aiCode.setDeptId(ShiroUtils.getSysUser().getCompanyId());
//                            //本公司下的条形码信息
//                            List<AICode> aiCodes1 = aiCodeMapper.selectAICode(aiCode);
//
//                            if (aiCodes1.size() != 0) {
//                                if (aiCodes.size() != 0) {
//                                    for (AICode code : aiCodes) {
//                                        code.setDeptId(ShiroUtils.getSysUser().getCompanyId());
//                                        code.setProductId(product.getProductId());
//                                    }
//                                    aiCodeMapper.updateAICodeList(aiCodes);
//                                }
//                            } else {
//                                if (aiCodes.size() != 0) {
//                                    for (AICode code : aiCodes) {
//                                        code.setDeptId(ShiroUtils.getSysUser().getCompanyId());
//                                        code.setProductId(product.getProductId());
//                                    }
//                                    aiCodeMapper.insertAICodeList(aiCodes);
//                                }
//                            }
                        }
                    } else {
                        Product product = new Product();
                        AICode aiCode = new AICode();
                        aiCode.setDeptId(supplierId);
                        aiCode.setProductId(productId1);
                        //供应商的产品条形码信息
                        List<AICode> aiCodes = aiCodeMapper.selectAICode(aiCode);
                        aiCode.setDeptId(sysUser.getCompanyId());
                        //本公司下的条形码信息
                        List<AICode> aiCodes1 = aiCodeMapper.selectAICode(aiCode);

                        product.setDeptId(sysUser.getCompanyId());
//                        if (productMapper.selectProductList(product) == null) {
                        product.setProductId(null);
                        product.setCreateBy(sysUser.getNickName());
                        productMapper.insertProduct(product);

                        Long productId = product.getProductId();
                        //将供应商的产品的条形码信息带到本公司下
                        if (aiCodes1.size() != 0) {
                            if (aiCodes.size() != 0) {
                                for (AICode code : aiCodes) {
                                    code.setDeptId(SecurityUtils.getLoginUser().getCompanyId());
                                    code.setProductId(product.getProductId());
                                }
                                aiCodeMapper.updateAICodeList(aiCodes);
                            }
                        } else {
                            if (aiCodes.size() != 0) {
                                for (AICode code : aiCodes) {
                                    code.setDeptId(sysUser.getCompanyId());
                                    code.setProductId(product.getProductId());
                                }
                                aiCodeMapper.insertAICodeList(aiCodes);
                            }

                        }
                        //查询图片集合
                        List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(productModelList.getModelNo());

                        //查询生产商信息，判断是否带回信息
                        DjManufacturer djManufacturer = djManufacturerMapper.selectDjManufacturerById(productModelList.getManufacturerId());
                        djManufacturer.setCompanyId(sysUser.getCompanyId());
                        DjManufacturer manufacturers = djManufacturerMapper.selectDjManufacturerOne(djManufacturer);
                        if (manufacturers == null) {
                            djManufacturer.setManufacturerId(null);
                            int i = djManufacturerMapper.insertDjManufacturer(djManufacturer);
                            productModelList.setManufacturerId(djManufacturer.getManufacturerId());
                        } else {
                            int i = djManufacturerMapper.updateDjManufacturer(djManufacturer);
                            productModelList.setManufacturerId(manufacturers.getManufacturerId());
                        }
                        productModelList.setProductId(productId);
                        productModelList.setDeptId(sysUser.getCompanyId());
                        productModelList.setCreateBy(sysUser.getNickName());
                        productMapper.insertProductModel(productModelList);
                        //循环赋值将产品规格中图片信息
                        if (pictureMemoryList.size() != 0) {
                            for (PictureMemory pictureMemory : pictureMemoryList) {
                                pictureMemory.setPictureNo(null);
                                pictureMemory.setModelNo(productModelList.getModelNo());
                            }
                            productMapper.insertPictureMemory(pictureMemoryList);
                        }
                    }
//                    }
                }
            }
        }
        return 1;
    }

    public void findModel(ProductModel productModel, Long i, String modelCode) {
        if (productMapper.selectProductByModelCode(ShiroUtils.getSysUser().getCompanyId(), modelCode) == null) {
            List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(productModel.getModelNo());
            productModel.setProductId(i);
            productModel.setDeptId(ShiroUtils.getSysUser().getCompanyId());
            productModel.setCreateBy(ShiroUtils.getLoginName());
            productMapper.insertProductModel(productModel);
            for (PictureMemory pictureMemory : pictureMemoryList) {
                pictureMemory.setModelNo(productModel.getModelNo());
            }
            productMapper.insertPictureMemory(pictureMemoryList);
        }
    }

    /**
     * 删除采购订单
     *
     * @param purchaseId 需要删除的主键
     * @return 结果
     */
    @Override
    public int deletePurchaseOrderById(Long purchaseId) {
        if (purchaseOrderMapper.selectPurchaseOrderByIds(purchaseId).size() != 0) {
            purchaseOrderMapper.deletePurchaseModelById(purchaseOrderMapper.selectPurchaseOrderByIds(purchaseId));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", purchaseId);
        map.put("orderType", "1");
        auditMapper.deleteAuditWith(map);
        return purchaseOrderMapper.deletePurchaseOrderById(purchaseId);
    }

    /**
     * 查询采购订单基础信息
     *
     * @param purchaseId 采购订单主键
     * @return 结果
     */
    @Override
    public PurchaseOrder selectPurchaseOrderById(Long purchaseId) {
        return purchaseOrderMapper.selectPurchaseOrderById(purchaseId);
    }

    /**
     * 查询采购订单规格型号信息
     *
     * @param purchaseId 采购订单主键
     * @return 结果
     */
    @Override
    public List<PurchaseModel> selectPurchaseModelById(Long purchaseId) {
        return purchaseOrderMapper.selectPurchaseModelByIds(purchaseId);
    }

    /**
     * 修改采购订单规格型号信息
     *
     * @param purchaseOrder 采购订单信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePurchaseOrder(PurchaseOrder purchaseOrder) {
        Product product1 = new Product();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        purchaseOrder.setUpdateBy(sysUser.getUserName());

        //添加审核订单
        Audit audit = new Audit();
        audit.setOrderId(purchaseOrder.getPurchaseId());
        audit.setCompanyId(sysUser.getCompanyId());
        audit.setOrderType("1");
        audit.setAuditStatus("0");
        audit.setUserId(purchaseOrder.getUserId());
        audit.setSupplierId(purchaseOrder.getSupplierId());
        audit.setTaxAmount(purchaseOrder.getTaxAmount());
        //订单编号
        audit.setOrderNum(purchaseOrder.getPurchaseNum());
        auditMapper.updateAuditOther(audit);

        //新建对比数组，用于判断执行什么操作
        ArrayList<Long> arrayList = new ArrayList();
        for (PurchaseModel model : purchaseOrderMapper.selectPurchaseModelById(purchaseOrder.getPurchaseId())) {
            arrayList.add(model.getModelId());
        }
        if (purchaseOrder.getPurchaseModel() != null) {
            List<PurchaseModel> purchaseModel = purchaseOrder.getPurchaseModel();
            //存储需要修改过的数据，用于后面的删除操作
            ArrayList<Long> purchaseModelList = new ArrayList();
            for (PurchaseModel model : purchaseModel) {
                model.setPurchaseId(purchaseOrder.getPurchaseId());
                if (model.getModelId() != null) {
                    purchaseOrderMapper.updatePurchaseModel(model);
                    purchaseModelList.add(model.getModelId());
                } else {
                    purchaseOrderMapper.insertPurchaseModels(model);
                }
            }

            //数组中剩余的数就是需要删除的数据
            for (int i = 0; i < purchaseModelList.size(); i++) {
                Iterator it = arrayList.iterator();
                while (it.hasNext()) {
                    if (purchaseModelList.get(i).equals(it.next())) {
                        it.remove();
                    }
                }
            }
            //判断是否需要删除
            if (arrayList.size() != 0) {
                purchaseOrderMapper.deletePurchaseModelById(arrayList);
            }

            //创建新的产品信息添加到自己的公司产品目录下
            List<PurchaseModel> purchaseModels = purchaseOrder.getPurchaseModel();
            if (purchaseModels.size() != 0) {
                Long supplierId = purchaseOrder.getSupplierId();
                for (PurchaseModel model : purchaseModels) {
                    Long productId1 = model.getProductId();
                    product1.setProductId(productId1);
                    product1.setDeptId(sysUser.getDeptId());
                    Product product = productMapper.selectProductById(product1);
                    //通过产品型号为一码查询产品信息 集合
                    String modelCode = model.getModelCode();
                    ProductModel productModelList = productMapper.selectProductByModelCode(supplierId, modelCode);
                    if (productMapper.selectProductByModelCode(sysUser.getCompanyId(), modelCode) != null) {
                        continue;
                    } else {
                        //查询供应商的产品注册证
                        ProductProof productProof = new ProductProof();
                        productProof.setDeptId(supplierId);
                        productProof.setProductId(model.getProductId());
                        List<ProductProof> productProofs = productProofMapper.selectProductProofList(productProof);
                        if (productProofs.size() != 0) {
                            //定义新的变量用于判断是否有该产品注册证信息
                            int count = 0;
                            for (ProductProof proof : productProofs) {
                                ProductProof productProof1 = new ProductProof();
                                productProof1.setDeptId(sysUser.getCompanyId());
                                productProof1.setMedicalNumber(proof.getMedicalNumber());
                                if (productProofMapper.selectProductProofList(productProof1).size() != 0) {
                                    if (productMapper.selectProductByModelCode(sysUser.getCompanyId(), modelCode) != null) {
                                        continue;
                                    }
                                    Long productId = productProofMapper.selectProductProofList(productProof1).get(0).getProductId();
                                    //查询图片集合
                                    List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(productModelList.getModelNo());
                                    //查询产品供应商信息，判断本公司下是否含有该供应商信息
                                    DjManufacturer djManufacturer = djManufacturerMapper.selectDjManufacturerById(productModelList.getManufacturerId());
                                    djManufacturer.setCompanyId(sysUser.getCompanyId());
                                    DjManufacturer manufacturers = djManufacturerMapper.selectDjManufacturerOne(djManufacturer);
                                    //有则修改产品供应商信息，没有则插入该生产商信息
                                    if (manufacturers == null) {
                                        djManufacturer.setManufacturerId(null);
                                        int i = djManufacturerMapper.insertDjManufacturer(djManufacturer);
                                        productModelList.setManufacturerId(djManufacturer.getManufacturerId());
                                    } else {
                                        int i = djManufacturerMapper.updateDjManufacturer(djManufacturer);
                                        productModelList.setManufacturerId(manufacturers.getManufacturerId());
                                    }
                                    //插入产品规格信息
                                    productModelList.setProductId(productId);
                                    productModelList.setDeptId(sysUser.getCompanyId());
                                    productMapper.insertProductModel(productModelList);
                                    //循环赋值将产品规格中图片信息
                                    if (pictureMemoryList.size() != 0) {
                                        for (PictureMemory pictureMemory : pictureMemoryList) {
                                            pictureMemory.setPictureNo(null);
                                            pictureMemory.setModelNo(productModelList.getModelNo());
                                        }
                                        productMapper.insertPictureMemory(pictureMemoryList);
                                    }
                                    count = 0;
                                    continue;
                                } else {
                                    count++;
                                }
                            }
                            if (count != 0) {
                                AICode aiCode = new AICode();
                                aiCode.setDeptId(supplierId);
                                aiCode.setProductId(productId1);
                                //供应商的产品条形码信息
                                List<AICode> aiCodes = aiCodeMapper.selectAICode(aiCode);
                                aiCode.setDeptId(sysUser.getCompanyId());
                                //本公司下的条形码信息
                                List<AICode> aiCodes1 = aiCodeMapper.selectAICode(aiCode);

                                product.setProductId(null);
                                product.setDeptId(sysUser.getCompanyId());
                                productMapper.insertProduct(product);

                                //将供应商下的产品注册证,带到本公司下
                                for (ProductProof proof : productProofs) {
                                    proof.setProductProofId(null);
                                    proof.setDeptId(sysUser.getCompanyId());
                                    proof.setProductId(product.getProductId());
                                    productProofMapper.insertProductProof(proof);
                                }
                                List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(productModelList.getModelNo());
                                //查询产品供应商信息
                                DjManufacturer djManufacturer = djManufacturerMapper.selectDjManufacturerById(productModelList.getManufacturerId());
                                djManufacturer.setCompanyId(sysUser.getCompanyId());
                                DjManufacturer manufacturers = djManufacturerMapper.selectDjManufacturerOne(djManufacturer);
                                if (manufacturers == null) {
                                    djManufacturer.setManufacturerId(null);
                                    int i = djManufacturerMapper.insertDjManufacturer(djManufacturer);
                                    productModelList.setManufacturerId(djManufacturer.getManufacturerId());
                                } else {
                                    int i = djManufacturerMapper.updateDjManufacturer(djManufacturer);
                                    productModelList.setManufacturerId(manufacturers.getManufacturerId());
                                }
                                //插入产品型号规格信息
                                productModelList.setProductId(product.getProductId());
                                productModelList.setDeptId(sysUser.getCompanyId());
                                productMapper.insertProductModel(productModelList);
                                //插入产品图片信息
                                if (pictureMemoryList.size() != 0) {
                                    for (PictureMemory pictureMemory : pictureMemoryList) {
                                        pictureMemory.setPictureNo(null);
                                        pictureMemory.setModelNo(productModelList.getModelNo());
                                    }
                                    productMapper.insertPictureMemory(pictureMemoryList);
                                }
                            }
                        } else {
                            AICode aiCode = new AICode();
                            aiCode.setDeptId(supplierId);
                            aiCode.setProductId(productId1);
                            //供应商的产品条形码信息
                            List<AICode> aiCodes = aiCodeMapper.selectAICode(aiCode);
                            aiCode.setDeptId(sysUser.getCompanyId());
                            //本公司下的条形码信息
                            List<AICode> aiCodes1 = aiCodeMapper.selectAICode(aiCode);

                            product.setDeptId(sysUser.getCompanyId());
                            product.setProductId(null);
                            productMapper.insertProduct(product);
                            Long productId = product.getProductId();
                            //将供应商的产品的条形码信息带到本公司下
                            if (aiCodes1.size() != 0) {
                                if (aiCodes.size() != 0) {
                                    for (AICode code : aiCodes) {
                                        code.setDeptId(sysUser.getCompanyId());
                                        code.setProductId(product.getProductId());
                                    }
                                    aiCodeMapper.updateAICodeList(aiCodes);
                                }
                            } else {
                                if (aiCodes.size() != 0) {
                                    for (AICode code : aiCodes) {
                                        code.setDeptId(sysUser.getCompanyId());
                                        code.setProductId(product.getProductId());
                                    }
                                    aiCodeMapper.insertAICodeList(aiCodes);
                                }
                            }
                            //查询图片集合
                            List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(productModelList.getModelNo());
                            //查询产品供应商信息
                            DjManufacturer djManufacturer = djManufacturerMapper.selectDjManufacturerById(productModelList.getManufacturerId());
                            djManufacturer.setCompanyId(sysUser.getCompanyId());
                            DjManufacturer manufacturers = djManufacturerMapper.selectDjManufacturerOne(djManufacturer);
                            if (manufacturers == null) {
                                djManufacturer.setManufacturerId(null);
                                int i = djManufacturerMapper.insertDjManufacturer(djManufacturer);
                                productModelList.setManufacturerId(djManufacturer.getManufacturerId());
                            } else {
                                int i = djManufacturerMapper.updateDjManufacturer(djManufacturer);
                                productModelList.setManufacturerId(manufacturers.getManufacturerId());
                            }
                            //插入产品规格信息
                            productModelList.setProductId(productId);
                            productModelList.setDeptId(sysUser.getCompanyId());
                            productMapper.insertProductModel(productModelList);
                            //循环赋值将产品规格中图片信息
                            if (pictureMemoryList.size() != 0) {
                                for (PictureMemory pictureMemory : pictureMemoryList) {
                                    pictureMemory.setPictureNo(null);
                                    pictureMemory.setModelNo(productModelList.getModelNo());
                                }
                                productMapper.insertPictureMemory(pictureMemoryList);
                            }
                        }
                    }
                }
            }
        } else {
            if (arrayList.size() != 0) {
                purchaseOrderMapper.deletePurchaseModelById(arrayList);
            }
        }
        return purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
    }

    /**
     * 查询供应商下的所有产品
     *
     * @param deptId 公司主键
     * @return 结果
     */
    @Override
    public List<Product> selectProduct(Long deptId) {
        return purchaseOrderMapper.selectProduct(deptId);
    }

    /**
     * 查询供应商下的所有产品     弹窗页面
     *
     * @return
     */
    @Override
    public List<Product> selectProductList(Product product) {

        return purchaseOrderMapper.selectProductList(product);
    }

    /**
     * 查询供应商下的所有产品   模糊查询
     *
     * @return
     */
    @Override
    public List<Product> selectProducts(Map map) {
        return purchaseOrderMapper.selectProducts(map);
    }

    /**
     * 查询产品下所有的规格型号
     *
     * @param productId 公司主键
     * @return 结果
     */
    @Override
    public List<ProductModel> selectProductModel(Long productId) {
        return purchaseOrderMapper.selectProductModel(productId);
    }


    /**
     * 生成订单编号
     *
     * @param date 日期
     * @param i    类型(0 采购订单 1 销售订单 2 销货单 3 销售发票)
     * @return
     */
    @Override
//    public synchronized String orderNum(Date date, int i) {
    public String orderNum(Date date, int i) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        //获取当前登录的用户
        Long companyId = sysUser.getCompanyId();
//        Long companyId = 101L;

        if (companyId == null) {
            return "0";
        }
        //定义订单前缀，获取订单的前缀
        String purPre;
        Parameter parameter = parameterMapper.selectParameterById(companyId);
        String num = "";
        if (parameter == null) {
            return "0";
        }
        //i 生成订单编号的类型
        if (i == 0) {
            //生成采购订单编号
            purPre = parameter.getPurPre();
            //查询采购订单
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            Map<String, Object> map = new HashMap<>();
            map.put("purchaseDate", date);
            map.put("deptId", sysUser.getCompanyId());
//            map.put("deptId", 101L);
            if (purchaseOrderMapper.selectPurchaseOrderNumList(map).size() != 0) {
                purchaseOrder = purchaseOrderMapper.selectPurchaseOrderNumList(map).get(0);
            }
            if (purchaseOrder.getPurchaseNum() == null) {
                int count = 1;
                num = "00" + count;
            } else {
                String purchaseNum = purchaseOrder.getPurchaseNum();
                String substring = purchaseNum.substring(purchaseNum.length() - 3);
                int count = Integer.parseInt(substring);
                if (count + 1 < 10) {
                    num = "00" + (count + 1);
                } else if (10 <= (count + 1) && (count + 1) < 100) {
                    num = "0" + (count + 1);
                } else {
                    num = "" + (count + 1);
                }
            }
        } else if (i == 1) {
            //生成销售订单编号
            purPre = parameter.getSalePre();
            Map<String, Object> map = new HashMap<>();
            map.put("saleorderDate", date);
            map.put("deptId", sysUser.getCompanyId());
//            map.put("deptId", 101L);
            //查询销售订单
            SaleorderOrder saleorderOrder = new SaleorderOrder();

            if (saleorderMapper.selectSaleorderByDate(map).size() > 0) {
                saleorderOrder = saleorderMapper.selectSaleorderByDate(map).get(0);
            }
            if (saleorderOrder.getSaleorderNum() == null) {
                int count = 1;
                num = "00" + count;
            } else {
                String saleorderNum = saleorderOrder.getSaleorderNum();
                String substring = saleorderNum.substring(saleorderNum.length() - 3);
                int count = Integer.parseInt(substring);
                if (count + 1 < 10) {
                    num = "00" + (count + 1);
                } else if (10 <= (count + 1) && (count + 1) < 100) {
                    num = "0" + (count + 1);
                } else {
                    num = "" + (count + 1);
                }
            }
        } else if (i == 2) {
            //生成出库订单编号
            purPre = parameter.getOutPre();
            Map<String, Object> map = new HashMap<>();
            map.put("saleGoodsDate", date);
            map.put("deptId", sysUser.getCompanyId());
//            map.put("deptId", 101L);
            map.put("params", null);

            //查询出库订单编号
            SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
            List<SaleGoodsOrder> saleGoodsOrderList = saleGoodsMapper.selectSaleGoodsListByMap(map);
            if (saleGoodsOrderList.size() > 0) {
                saleGoodsOrder = saleGoodsOrderList.get(0);
            }
            if (saleGoodsOrder.getSaleGoodsNum() == null) {
                int count = 1;
                num = "00" + count;
            } else {
                String invoiceNum = saleGoodsOrder.getSaleGoodsNum();
                String substring = invoiceNum.substring(invoiceNum.length() - 3);
                int count = Integer.parseInt(substring);
                if (count + 1 < 10) {
                    num = "00" + (count + 1);
                } else if (10 <= (count + 1) && (count + 1) < 100) {
                    num = "0" + (count + 1);
                } else {
                    num = "" + (count + 1);
                }
            }
        } else if (i == 3) {
            //生成销售发票编号
            purPre = parameter.getInvoicePre();
            Map<String, Object> map = new HashMap<>();
            map.put("invoiceDate", date);
            map.put("deptId", sysUser.getCompanyId());
//            map.put("deptId", 101L);
//            map.put("params", null);

            //查询销售发票信息
            SalesInvoiceOrder salesInvoiceOrder = new SalesInvoiceOrder();
            List<SalesInvoiceOrder> salesInvoiceOrders = salesInvoiceMapper.selectSalesInvoiceByMap(map);
            if (salesInvoiceOrders.size() > 0) {
                salesInvoiceOrder = salesInvoiceOrders.get(0);
            }
            if (salesInvoiceOrder.getSalesInvoiceNum() == null) {
                int count = 1;
                num = "00" + count;
            } else {
                String invoiceNum = salesInvoiceOrder.getSalesInvoiceNum();
                String substring = invoiceNum.substring(invoiceNum.length() - 3);
                int count = Integer.parseInt(substring);
                if (count + 1 < 10) {
                    num = "00" + (count + 1);
                } else if (10 <= (count + 1) && (count + 1) < 100) {
                    num = "0" + (count + 1);
                } else {
                    num = "" + (count + 1);
                }
            }
        } else {
            //入库订单编号
            purPre = parameter.getStockPre();
            //查询入库订单
            ProcurementOrder procurementOrder = new ProcurementOrder();
            Map<String, Object> map = new HashMap<>();
            map.put("procurementWarehousingDate", date);
            map.put("deptId", companyId);
            if (procurementOrderMapper.selectProcurementWarehousingNameList(map).size() > 0) {
                procurementOrder = procurementOrderMapper.selectProcurementWarehousingNameList(map).get(0);
            }
            if (procurementOrder.getProcurementWarehousingName() == null) {
                int count = 1;
                num = "00" + count;
            } else {
                String purchaseNum = procurementOrder.getProcurementWarehousingName();
                String substring = purchaseNum.substring(purchaseNum.length() - 3);
                int count = Integer.parseInt(substring);
                if (count + 1 < 10) {
                    num = "00" + (count + 1);
                } else if (10 <= (count + 1) && (count + 1) < 100) {
                    num = "0" + (count + 1);
                } else {
                    num = "" + (count + 1);
                }
            }
        }
        //获取输入框日期
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
//        String localDate = simpleDateFormat.format(date);


        SimpleDateFormat simpleDateFormats = new SimpleDateFormat("yyMMdd");
        String localDate = simpleDateFormats.format(date);
        String s = String.valueOf(new Date().getTime());
        String substring = s.substring(s.length() - 3);


        String orderNum = purPre + "-" + localDate + substring + "-" + num;
//        String orderNum = purPre + "-" + localDate + "-" + num;

        return orderNum;
    }

    /**
     * 查询未审核采购订单
     *
     * @param purchaseOrder 查询条件
     * @return 结果
     */
    @Override
    public List<PurchaseOrder> selectPurchaseSupplier(PurchaseOrder purchaseOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        purchaseOrder.setDeptId(sysUser.getCompanyId());
        return purchaseOrderMapper.selectPurchaseSupplier(purchaseOrder);
    }

    /**
     * 复制采购订单
     *
     * @param purchaseId 主键
     * @return 结果
     */
    @Override
    public int copyPurchaseOrderById(Long purchaseId) {
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderById(purchaseId);
        List<PurchaseModel> purchaseModels = purchaseOrderMapper.selectPurchaseModelById(purchaseId);
        purchaseOrder.setPurchaseId(null);
        purchaseOrder.setPurchaseStatus("0");
        purchaseOrder.setAuditTime(null);
        //使用SimpleDateFormat的parse()方法生成Date
        SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dates = a.parse(a.format(new Date()));
            purchaseOrder.setPurchaseDate(dates);
            purchaseOrder.setPurchaseNum(orderNum(dates, 0));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        purchaseOrderMapper.insertPurchaseOrder(purchaseOrder);
        if (purchaseModels.size() != 0) {
            for (int i = 0; i < purchaseModels.size(); i++) {
                PurchaseModel purchaseModel = purchaseModels.get(i);
                purchaseModel.setPurchaseId(purchaseOrder.getPurchaseId());
                purchaseOrderMapper.insertPurchaseModels(purchaseModel);
            }
        }
        //添加审核订单
        Audit audit = new Audit();
        audit.setOrderId(purchaseOrder.getPurchaseId());
        audit.setCompanyId(ShiroUtils.getSysUser().getCompanyId());
        audit.setOrderType("1");
        audit.setAuditStatus("0");
        audit.setUserId(purchaseOrder.getUserId());
        audit.setSupplierId(purchaseOrder.getSupplierId());
        audit.setTaxAmount(purchaseOrder.getTaxAmount());
        //订单编号
        audit.setOrderNum(purchaseOrder.getPurchaseNum());
        auditMapper.insertAudit(audit);
        return 1;
    }

    /**
     * 查询采购订单信息
     *
     * @param hashMap 查询条件
     * @return 结果
     */
    @Override
    public PurchaseOrder selectPurchaseOrderByMap(HashMap<String, Object> hashMap) {
        return purchaseOrderMapper.selectPurchaseOrderByMap(hashMap);
    }

    /**
     * 查询产品型号规格信息
     *
     * @param product 查询条件
     * @return 结果
     */
    @Override
//    public TableDataInfo selectProductLists(Product product) {
//        List<Long> longs = productMapper.selectProductModelByDeptId(product);
//        TableDataInfo rspData = new TableDataInfo();
//        if (longs.size() == 0) {
//            rspData.setCode(0);
//            rspData.setTotal(0);
//            rspData.setRows(new ArrayList<ProductModel>());
//            return rspData;
//        }
//        rspData.setCode(0);
//        rspData.setTotal(new PageInfo(longs).getTotal());
////        List<ProductModel> productModelList = purchaseOrderMapper.selectProductLists(longs);
//        List<ProductModel> productModelList = purchaseOrderMapper.selectProductLists(product);
//        rspData.setRows(productModelList);
//        return rspData;
//    }
    public List<ProductModel> selectProductLists(Product product) {
        List<ProductModel> productModelList = purchaseOrderMapper.selectProductLists(product);
        return productModelList;
    }

    /**
     * 根据 ModelCode查询 最新订单的价格
     */
    @Override
    public List<BigDecimal> selectSaleorderNewPrice(HashMap hashMap) {
        return purchaseOrderMapper.selectSaleorderNewPrice(hashMap);
    }

    @Override
    public int updatePurchaseModel(PurchaseModel purchaseModel) {
        return purchaseOrderMapper.updatePurchaseModel(purchaseModel);
    }


    @Override
    public Long querypreviousId(Long purchaseId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("purchaseId", purchaseId);
        params.put("deptId", SecurityUtils.getDeptId());
        return purchaseOrderMapper.querypreviousId(params);
    }

    @Override
    public Long queryNextId(Long purchaseId) {
        Map<String, Object> params = new HashMap<>();
        params.put("purchaseId", purchaseId);
        params.put("deptId", SecurityUtils.getDeptId());
        return purchaseOrderMapper.queryNextId(params);
    }

    @Override
    public List<Map<String, Object>> pendingReview(Long deptId) {
        return purchaseOrderMapper.pendingReview(deptId)
                .stream()
                .peek(item -> item.put("orderType", "采购订单"))
                .collect(Collectors.toList());
    }
}
